/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import com.mvc.login.UserBean;
import com.ptit.classlearning.ConClass;
import com.ptit.student.Student;
import com.ptit.subject.Subject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

/**
 *
 * @author Admin
 */
@WebServlet(name = "Controller", urlPatterns = {"/Controller"})
public class Controller extends HttpServlet {

    final private String errorPage = "login.jsp";
    final private String homePage = "index.jsp";
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String url = errorPage;
            String action  = request.getParameter("requestAction");
             String tb = "";
                    
            if(action.equals("Login"))
            {
                if(login(request,response))
                     url = "index.jsp";   
                else 
                {
                    tb = "Đăng nhập thất bại, vui lòng thử lại";
                    url = "login.jsp?tb=" + tb;
                }
                 
            }
           else  if(action.equals("showAllStudents")){
                Student sv=new Student();    
                sv.connect();
                tb=sv.showAll();
               sv.disconnect();
                url="/ManageStudent.jsp?tb="+tb;
            }
           else   if(action.equals("addStudent")) 
            {
          
                 tb = addStudent(request, response);
                 
          //      if(tb.equals(""))
         //          tb= "Thêm sinh viên thành công";             
                url = "/ManageStudent.jsp";
                
                  
                 
            }
           else  if (action.equals("deleteStudent")) {
                deleteStudent(request, response);
                url = "/ManageStudent.jsp";
            }
           else if(action.equals("editStudent"))
           {
               tb=editStudent(request,response);
               if(tb.equals("")) 
                    url = "/ManageStudent.jsp";
               else 
                   url = "/EditStudent.jsp?tb="+tb;
           }
           else if(action.equals("searchStudent"))
           {      
               boolean searchName = false;
               
               if(request.getParameter("optionSearch").trim().equals("Theo tÃªn sinh viÃªn"))
                   searchName =true;
                Student sv=new Student();    
                sv.connect();
                tb=sv.searchStudent(request.getParameter("txtSearch").trim(),searchName);
                sv.disconnect();
                url="/SearchStudent.jsp?tb="+tb;
           }
           
           else if(action.equals("showClassName"))
                {
                    String menu;
                    ConClass conClass = new ConClass();
                    conClass.connect();
                   menu=  conClass.showClassName();
                   conClass.disconnect();
                   url="/AddStudent.jsp?menu="+menu;
                }
           else if (action.equals("showAllClass"))
                {
                ConClass conClass =new ConClass();    
                conClass.connect();
                tb=conClass.showAll();
                 conClass.disconnect();
                url="/ManageClass.jsp?tb="+tb;
                }
           else if(action.equals("deleteClass"))
           {
               
               String noticeDelete = deleteClass(request, response);
                url = "/ManageClass.jsp?noticeDelete="+noticeDelete;
           }
             else if(action.equals("addClass"))
           {
               
                tb = addClass(request, response);
                url = "/ManageClass.jsp?tb="+tb;
           }
             else if(action.equals(("editClass")))
             {
                 tb = editClass(request,response);
                 if(tb.equals("")) 
                     url = "/ManageClass.jsp?tb=";
                  else
                       url = "/EditClass.jsp?tb="+tb;
             }
           else  if(action.equals("showAllSubject")){
                Subject subject =new Subject();    
                subject.connect();
                tb=subject.showAll();
               subject.disconnect();
                url="/ManageSubject.jsp?tb="+tb;
            }
           else if(action.equals(("editSubject")))
             {
                 tb = editSubject(request,response);
                 if(tb.equals("")) 
                     url = "/ManageSubject.jsp?tb=";
                  else
                       url = "/EditSubject.jsp?tb="+tb;
             }
            else if(action.equals("deleteSubject"))
           {
               
               String noticeDelete = deleteSubject(request, response);
                url = "/ManageSubject.jsp?noticeDelete="+noticeDelete;
           }
                else if(action.equals("addSubject"))
           {
               
                tb = addSubject(request, response);
                url = "/ManageSubject.jsp?tb="+tb;
           }
                RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);
        }catch(Exception e)
        {
        } finally {            
            out.close();
        }
    }
    
    public boolean login(HttpServletRequest request, HttpServletResponse response)
    {
          String username  = request.getParameter("txtUsername");
          String password = request.getParameter("txtPassword"); 
          UserBean login = new UserBean();
         boolean result =  login.checkLogin(username,password);
        
            if(result)
            {
                HttpSession session = request.getSession(true);
                session.setAttribute("User",username);
                return true;
            }
            return false;
    }
    public String addStudent(HttpServletRequest request, HttpServletResponse response) {
        String tb = "";
    
        try {
            String mssv = request.getParameter("txtStudentID");
            String name = request.getParameter("txtStudentName");
            
            String birth = request.getParameter("txtStudentBirth");
            String gender = request.getParameter("rdoGender");
            
            String createdDate = request.getParameter("txtStudentCreated");
            String classLearning = request.getParameter("optionClass");
            ConClass conClass = new ConClass();
         
            String classID =  conClass.selectClassID(classLearning);
            Student newStudent = new Student(mssv,name,birth,createdDate,classID,gender);      
            newStudent.addStudent();
                    
            }
         catch (Exception ex) {
            tb="Thêm sinh viên bị lỗi" +ex;
        }
     
        return tb;
}
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        String studentID = request.getParameter("studentID");
        Student student = new Student();
        student.deleteStudent(studentID);
        
    }

    private String editStudent(HttpServletRequest request, HttpServletResponse response){
        String tb ="";
        try{
        String studentID = request.getParameter("txtStudentID");
         String name = request.getParameter("txtStudentName");     
         String birth = request.getParameter("txtStudentBirth");
         String gender = request.getParameter("rdoGender"); 
          String createdDate = request.getParameter("txtStudentCreated");
          String classLearning = request.getParameter("txtClass");
          ConClass conClass = new ConClass();
          String classID =  conClass.selectClassID(classLearning);
         Student newStudent = new Student(studentID,name,birth,createdDate,classID,gender);  
         newStudent.editStudent();
         } catch (Exception ex) {
            tb="Cập nhật sinh viên bị lỗi" +ex;
         }
        return tb;
    }
    public String addClass(HttpServletRequest request, HttpServletResponse response) {
        String tb = "";
        try {
            String class_name = request.getParameter("class_name");
            
            String major = request.getParameter("major");

            ConClass newClass = new ConClass(class_name,major);      
            newClass.addClass();
                    
            }
         catch (Exception ex) {
            tb="Thêm lớp bị lỗi" +ex;
        }
     
        return tb;
} 
    public String deleteClass(HttpServletRequest request, HttpServletResponse response)  {
       String tb="";
       try{
        String classID = request.getParameter("classID");
        ConClass classes = new ConClass();
        classes.connect();
        int capacity = classes.selectCapacity(classID);
        classes.disconnect();
        if(capacity==0)
            classes.deleteClass(classID);
        else 
        {
            tb = "Không thể xóa lớp khi đang chứa sinh viên";
             JOptionPane.showMessageDialog(null,"Không thể xóa lớp khi đang chứa sinh viên" );
       
       }
       }
       catch(Exception e)
       {
           tb = "Lỗi: "+e;
           }
        return tb;
   
   } 
    
    public String addSubject(HttpServletRequest request, HttpServletResponse response) {
        String tb = "";
        try {
            String subject_name = request.getParameter("subject_name");                  
            int score_1_ratio = Integer.parseInt(request.getParameter("score_1_ratio"));
            int score_2_ratio = Integer.parseInt(request.getParameter("score_2_ratio"));
            int score_3_ratio = Integer.parseInt(request.getParameter("score_3_ratio"));          
            String subject_id = request.getParameter("subject_id");
            int number_of_section= Integer.parseInt(request.getParameter("number_of_section"));
            Subject newSubject = new Subject(subject_name,subject_id,score_1_ratio,score_2_ratio,score_3_ratio,number_of_section);      
            newSubject.addSubject();
                    
            }
         catch (Exception ex) {
            tb="Thêm môn học bị lỗi" +ex;
        }
     
        return tb;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private String editClass(HttpServletRequest request, HttpServletResponse response) {
         String tb ="";
        try{
        String class_id = request.getParameter("hiddenClassID");
        String class_name = request.getParameter("txtClassName");
         String major = request.getParameter("txtMajor");     
          ConClass conClass = new ConClass(class_name,major);
          conClass.setClassID(class_id);
           conClass.editClass();
   
         
       
         } catch (Exception ex) {
            tb="Cập nhật lớp  bị lỗi" +ex;
         }
        return tb;
    }

    private String editSubject(HttpServletRequest request, HttpServletResponse response) {
       String tb ="";
        try{
        String stt_id = request.getParameter("hiddenSubjectID");
        String subject_name = request.getParameter("txtSubjectName");
        String subject_id = request.getParameter("txtSubjectID");
        String score_1_ratio = request.getParameter("txt_score_1_ratio");
        String score_2_ratio = request.getParameter("txt_score_2_ratio");
        String score_3_ratio = request.getParameter("txt_score_3_ratio");
        String number_of_section = request.getParameter("txt_number_of_section");
        Subject subjectSelected = new Subject(subject_name,subject_id
                ,Integer.parseInt(score_1_ratio)
                 ,Integer.parseInt(score_2_ratio)
                 ,Integer.parseInt(score_3_ratio)
                  ,Integer.parseInt(number_of_section));
        subjectSelected.setStt_id(stt_id);
                
     
        subjectSelected.editSubject();
   
         
       
         } catch (Exception ex) {
            tb="Cập nhật lớp  bị lỗi" +ex;
         }
        return tb;
    }

    private String deleteSubject(HttpServletRequest request, HttpServletResponse response) {
        String tb="";
       try{
        String stt_id = request.getParameter("stt_id");
        Subject subjectSelected = new Subject();       
    
        subjectSelected.deleteSubject(stt_id);
       }
       catch(Exception e)
       {
           tb = "Lỗi: "+e;
           }
        return tb;
   
    }

   
}
